import axios from 'axios';
//import notification from 'element-ui';
import { VueAxios } from './axios';
import store from '@/store';
import { Message, Loading } from 'element-ui'
// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL,
  //baseURL: "http://localhost:8864",
  timeout: 20000,
  withCredentials: true
});


/* 当页面有两个接口时，第一个接口loading的close事件会直接将第二个接口的loading实例也close */
let loadingInstance = null
function startLoading () {
  loadingInstance = Loading.service({
    fullscreen: true,
    text: '拼命加载中...',
    background: 'rgba(0, 0, 0, 0.8)'
  })
}
function endLoading () {
  loadingInstance.close()
}
let needLoadingRequestCount = 0
function showFullScreenLoading () {
  if (needLoadingRequestCount === 0) {
    startLoading()
  }
  needLoadingRequestCount++
}
function tryHideFullScreenLoading () {
  if (needLoadingRequestCount <= 0) return
  needLoadingRequestCount--
  if (needLoadingRequestCount === 0) {
    endLoading()
  }
}

const err = error => {
  tryHideFullScreenLoading()
  if (error.response) {
    const data = error.response.data;
    const token = store.getters.accessToken;
    if (error.response.status === 403) {
      Message({
        message: '接口Forbidden:' || data.errMsg,
        type: 'error'
      });
    }
    if (error.response.status === 401 || error.response.status === 500) {
      Message({
        message: '安全认证:' + error.response.data.errMsg,
        type: 'error',
      });
      if (token) {
        store.dispatch('Logout').then(() => {
          setTimeout(() => {
            window.location.href = '/';
          }, 1500);
        });
      }
    }
  }
  return Promise.reject(error);
};

service.interceptors.request.use(config => {
  let url = config.url;
  if (url.split('/').pop() !== 'qrymsg') {
    showFullScreenLoading();
  }
  // showFullScreenLoading();
  const token = store.getters.accessToken;
  const userId = store.getters.userId;
  if (token) {
    config.headers['token'] = token; // 让每个请求携带自定义tokens
    config.headers['userId'] = userId;
  }
  return config;
}, err);

// response interceptor
service.interceptors.response.use(response => {
  tryHideFullScreenLoading()
  const token = response.headers.token;
  // console.log(response.headers);
  //console.log(response);
  if (token) {
    store.dispatch('renewToken', token);
  }
  return response.data;
}, err);

const installer = {
  vm: {},
  install (Vue) {
    Vue.use(VueAxios, service);
  }
};

export { installer as VueAxios, service as axios };
